package hgx.spring.cloud.lession.productrepertory.hystrix;/**
 * Created by liujun on 2018/4/21.
 */

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;

import hgx.spring.cloud.lession.productrepertory.api.ProductRepository;
import hgx.spring.cloud.lession.productrepertory.vo.ProductVo;
import hgx.spring.cloud.lession.productrepertory.vo.ReponseProductVo;

/**
 * 查询所有产品
 * @author hugx
 * @create 2018-04-21 10:31
 */
public class ProductGetByIdHystrixCommand extends HystrixCommand<ReponseProductVo> {
    private ProductRepository productRepository;
    private Long id;
    private static final  HystrixCommandKey GetById_Key=HystrixCommandKey.Factory.asKey("product_getById");

    public ProductGetByIdHystrixCommand(ProductRepository productRepository,Long id) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(ProductCommandEnum.Product_Get_Set_GroupKey.getKey())).andCommandKey(GetById_Key));
        this.productRepository = productRepository;
        this.id=id;
    }


    @Override
    protected ReponseProductVo run() throws Exception {
        long startTime = System.currentTimeMillis();
        System.out.println("执行 断路器命令的run() 方法 ,  keyName: " + getCommandKey().name());

        ReponseProductVo reponse = new ReponseProductVo();
        ProductVo productVo = productRepository.getProductById(id);
        if (productVo !=null) {
            reponse.setProductVo(productVo);
            reponse.success();
        }

        System.out.println("3: ----------------run() ,耗时: " + (System.currentTimeMillis() - startTime));
        return reponse;
    }

    @Override
    protected ReponseProductVo getFallback() {
        System.out.println("3.1: ----------------getFallback()  ");
        ReponseProductVo reponse = new ReponseProductVo();
        return reponse;
    }

    @Override
    protected String getCacheKey() {
        /*根据查询条件置入缓存*/
        System.out.println("4.1-------------------------从缓存中获取数据");
        String result=String.valueOf(this.id);
        System.out.println("4.2-------------------------从缓存中获取数据 ， cacheKey: "+result);
        return result;
    }

    public static void flushCache(Long id){
        /*刷新缓坡，根据查询条件进行清理*/
        HystrixRequestCache.getInstance(GetById_Key, HystrixConcurrencyStrategyDefault.getInstance()).clear(String.valueOf(id));
    }
}
